package com.tzkyzj.tiremanagersystem.ui;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.checkbox.MaterialCheckBox;
import com.google.android.material.textfield.MaterialAutoCompleteTextView;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.tzkyzj.tiremanagersystem.R;
import com.tzkyzj.tiremanagersystem.eneities.Tire;
import com.tzkyzj.tiremanagersystem.api.TireApiService;
import com.tzkyzj.tiremanagersystem.network.ApiClient;
import com.tzkyzj.tiremanagersystem.network.ApiResponse;
import com.tzkyzj.tiremanagersystem.utils.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddSwapActivity extends AppCompatActivity {

    private static final int REQUEST_PICK_IMAGES = 1001;

    private Tire tire;
    private TireApiService apiService;

    // 视图组件
    private MaterialCardView cardSwap, cardScrap;
    private TextInputEditText etSwapDate, etSwapMileage, etSwapCost;
    private TextInputEditText etFromVehiclePlate, etFromTrailerPlate;
    private MaterialAutoCompleteTextView spFromAxle, spFromPosition;
    private TextInputEditText etToVehiclePlate, etToTrailerPlate;
    private MaterialAutoCompleteTextView spToAxle, spToPosition;
    private TextInputEditText etSwapNote;
    private MaterialCheckBox cbConfirmScrap;
    private MaterialButton btnSelectPhotos, btnSubmit;
    private RecyclerView rvPhotos;

    private List<Uri> selectedPhotos = new ArrayList<>();
    private PhotoAdapter photoAdapter;

    private String operationType = "swap"; // 默认正常调胎

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_swap);

        // 获取传递的轮胎数据
        tire = (Tire) getIntent().getSerializableExtra("tire");
        if (tire == null) {
            finish();
            return;
        }

        // 初始化API服务
        apiService = ApiClient.getClient().create(TireApiService.class);

        initViews();
        setupToolbar();
        setupSpinners();
        setupClickListeners();
        setupPhotoRecyclerView();
        setDefaultValues();
    }

    private void initViews() {
        // 操作类型卡片
        cardSwap = findViewById(R.id.cardSwap);
        cardScrap = findViewById(R.id.cardScrap);

        // 表单字段
        etSwapDate = findViewById(R.id.etSwapDate);
        etSwapMileage = findViewById(R.id.etSwapMileage);
        etSwapCost = findViewById(R.id.etSwapCost);

        etFromVehiclePlate = findViewById(R.id.etFromVehiclePlate);
        etFromTrailerPlate = findViewById(R.id.etFromTrailerPlate);
        spFromAxle = findViewById(R.id.spFromAxle);
        spFromPosition = findViewById(R.id.spFromPosition);

        etToVehiclePlate = findViewById(R.id.etToVehiclePlate);
        etToTrailerPlate = findViewById(R.id.etToTrailerPlate);
        spToAxle = findViewById(R.id.spToAxle);
        spToPosition = findViewById(R.id.spToPosition);

        etSwapNote = findViewById(R.id.etSwapNote);
        cbConfirmScrap = findViewById(R.id.cbConfirmScrap);

        btnSelectPhotos = findViewById(R.id.btnSelectPhotos);
        btnSubmit = findViewById(R.id.btnSubmit);
        rvPhotos = findViewById(R.id.rvPhotos);
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            if (getSupportActionBar() != null) {
                getSupportActionBar().setTitle("添加调胎记录 - " + tire.getTireNumber());
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            }
        }
    }

    private void setupSpinners() {
        // 轴号选项
        String[] axleOptions = {"1", "2", "3", "4", "5", "6"};
        ArrayAdapter<String> axleAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, axleOptions);
        spFromAxle.setAdapter(axleAdapter);
        spToAxle.setAdapter(axleAdapter);

        // 位置选项
        String[] positionOptions = {"左内", "左外", "右内", "右外"};
        ArrayAdapter<String> positionAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, positionOptions);
        spFromPosition.setAdapter(positionAdapter);
        spToPosition.setAdapter(positionAdapter);
    }

    private void setupClickListeners() {
        // 操作类型选择
        cardSwap.setOnClickListener(v -> selectOperationType("swap"));
        cardScrap.setOnClickListener(v -> selectOperationType("scrap"));

        // 日期选择
        etSwapDate.setOnClickListener(v -> showDatePicker());

        // 选择照片
        btnSelectPhotos.setOnClickListener(v -> selectPhotos());

        // 提交表单
        btnSubmit.setOnClickListener(v -> submitSwapRecord());
    }

    private void setupPhotoRecyclerView() {
        photoAdapter = new PhotoAdapter(selectedPhotos);
        rvPhotos.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        rvPhotos.setAdapter(photoAdapter);
    }

    private void setDefaultValues() {
        // 设置当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        etSwapDate.setText(sdf.format(new java.util.Date()));

        // 设置当前公里数
        if (tire.getCurrentMileage() != null) {
            etSwapMileage.setText(String.valueOf(tire.getCurrentMileage()));
        }

        // 设置调胎前位置为轮胎当前位置
        etFromVehiclePlate.setText(tire.getVehiclePlateNumber());
        etFromTrailerPlate.setText(tire.getTrailerPlateNumber());
        if (tire.getAxleNumber() != null) {
            spFromAxle.setText(String.valueOf(tire.getAxleNumber()), false);
        }
        if (tire.getTirePosition() != null) {
            spFromPosition.setText(tire.getTirePosition(), false);
        }

        // 默认选择正常调胎
        selectOperationType("swap");
    }

    private void selectOperationType(String type) {
        operationType = type;

        if ("swap".equals(type)) {
            cardSwap.setCardBackgroundColor(getColor(R.color.selected_card_background));
            cardScrap.setCardBackgroundColor(getColor(R.color.card_background));

            // 显示调胎后位置，隐藏报废确认
            findViewById(R.id.layoutToPosition).setVisibility(View.VISIBLE);
            findViewById(R.id.layoutScrapConfirmation).setVisibility(View.GONE);

            btnSubmit.setText("保存调胎记录");
        } else {
            cardSwap.setCardBackgroundColor(getColor(R.color.card_background));
            cardScrap.setCardBackgroundColor(getColor(R.color.selected_card_background));

            // 隐藏调胎后位置，显示报废确认
            findViewById(R.id.layoutToPosition).setVisibility(View.GONE);
            findViewById(R.id.layoutScrapConfirmation).setVisibility(View.VISIBLE);

            btnSubmit.setText("确认报废");
        }
    }

    private void showDatePicker() {
        final Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String selectedDate = String.format(Locale.getDefault(),
                                "%d-%02d-%02d", year, month + 1, dayOfMonth);
                        etSwapDate.setText(selectedDate);
                    }
                }, year, month, day);
        datePickerDialog.show();
    }

    private void selectPhotos() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        startActivityForResult(Intent.createChooser(intent, "选择照片"), REQUEST_PICK_IMAGES);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_PICK_IMAGES && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                if (data.getClipData() != null) {
                    // 多选照片
                    int count = data.getClipData().getItemCount();
                    for (int i = 0; i < count; i++) {
                        Uri imageUri = data.getClipData().getItemAt(i).getUri();
                        selectedPhotos.add(imageUri);
                    }
                } else if (data.getData() != null) {
                    // 单选照片
                    selectedPhotos.add(data.getData());
                }
                photoAdapter.notifyDataSetChanged();
            }
        }
    }

    private void submitSwapRecord() {
        if (!validateInput()) {
            return;
        }

        showLoading(true);

        try {
            // 构建Multipart请求 - 使用新的createPhotoParts方法
            List<MultipartBody.Part> photoParts = createPhotoParts();

            // 构建其他表单字段
            RequestBody swapDate = RequestBody.create(MediaType.parse("text/plain"),
                    etSwapDate.getText().toString());
            RequestBody swapMileage = RequestBody.create(MediaType.parse("text/plain"),
                    etSwapMileage.getText().toString());
            RequestBody swapCost = RequestBody.create(MediaType.parse("text/plain"),
                    etSwapCost.getText().toString());
            RequestBody operationTypeBody = RequestBody.create(MediaType.parse("text/plain"),
                    operationType);

            // 调胎前位置
            RequestBody fromVehiclePlateNumber = RequestBody.create(MediaType.parse("text/plain"),
                    getTextOrEmpty(etFromVehiclePlate));
            RequestBody fromTrailerPlateNumber = RequestBody.create(MediaType.parse("text/plain"),
                    getTextOrEmpty(etFromTrailerPlate));
            RequestBody fromAxleNumber = RequestBody.create(MediaType.parse("text/plain"),
                    getTextOrEmpty(spFromAxle));
            RequestBody fromTirePosition = RequestBody.create(MediaType.parse("text/plain"),
                    getTextOrEmpty(spFromPosition));

            // 调胎后位置（仅正常调胎时需要）
            RequestBody toVehiclePlateNumber = RequestBody.create(MediaType.parse("text/plain"),
                    "swap".equals(operationType) ? getTextOrEmpty(etToVehiclePlate) : "");
            RequestBody toTrailerPlateNumber = RequestBody.create(MediaType.parse("text/plain"),
                    "swap".equals(operationType) ? getTextOrEmpty(etToTrailerPlate) : "");
            RequestBody toAxleNumber = RequestBody.create(MediaType.parse("text/plain"),
                    "swap".equals(operationType) ? getTextOrEmpty(spToAxle) : "");
            RequestBody toTirePosition = RequestBody.create(MediaType.parse("text/plain"),
                    "swap".equals(operationType) ? getTextOrEmpty(spToPosition) : "");

            // 备注和确认
            RequestBody swapNote = RequestBody.create(MediaType.parse("text/plain"),
                    getTextOrEmpty(etSwapNote));
            RequestBody confirmScrap = RequestBody.create(MediaType.parse("text/plain"),
                    String.valueOf(cbConfirmScrap.isChecked()));

            // 将List转换为数组（如果API需要数组格式）
            MultipartBody.Part[] photoPartsArray = photoParts.toArray(new MultipartBody.Part[0]);

            // 调用API
            Call<ApiResponse<Void>> call = apiService.addSwapRecord(
                    tire.getId(), swapDate, swapMileage, swapCost,
                    fromVehiclePlateNumber, fromTrailerPlateNumber, fromAxleNumber, fromTirePosition,
                    toVehiclePlateNumber, toTrailerPlateNumber, toAxleNumber, toTirePosition,
                    swapNote, operationTypeBody, confirmScrap, photoPartsArray);

            call.enqueue(new Callback<ApiResponse<Void>>() {
                @Override
                public void onResponse(Call<ApiResponse<Void>> call, Response<ApiResponse<Void>> response) {
                    showLoading(false);

                    if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                        Toast.makeText(AddSwapActivity.this,
                                "swap".equals(operationType) ? "调胎记录添加成功" : "调胎报废成功",
                                Toast.LENGTH_SHORT).show();

                        setResult(Activity.RESULT_OK);
                        finish();
                    } else {
                        String errorMsg = "提交失败";
                        if (response.body() != null) {
                            errorMsg += ": " + response.body().getMessage();
                        } else if (response.errorBody() != null) {
                            try {
                                errorMsg += ": " + response.errorBody().string();
                            } catch (IOException e) {
                                Log.e("AddSwapActivity", "读取错误响应失败", e);
                            }
                        }
                        Toast.makeText(AddSwapActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<ApiResponse<Void>> call, Throwable t) {
                    showLoading(false);
                    Toast.makeText(AddSwapActivity.this,
                            "提交失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                    Log.e("AddSwapActivity", "网络请求失败", t);
                }
            });

        } catch (Exception e) {
            showLoading(false);
            Toast.makeText(this, "提交异常: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e("AddSwapActivity", "提交异常", e);
        }
    }

    private boolean validateInput() {
        // 基本验证
        if (TextUtils.isEmpty(etSwapDate.getText())) {
            Toast.makeText(this, "请选择操作日期", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (TextUtils.isEmpty(etSwapMileage.getText())) {
            Toast.makeText(this, "请输入公里数", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (TextUtils.isEmpty(etSwapCost.getText())) {
            Toast.makeText(this, "请输入费用", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 调胎报废需要确认
        if ("scrap".equals(operationType) && !cbConfirmScrap.isChecked()) {
            Toast.makeText(this, "请确认报废操作", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 正常调胎需要调胎后位置
        if ("swap".equals(operationType)) {
            if (TextUtils.isEmpty(etToVehiclePlate.getText()) &&
                    TextUtils.isEmpty(etToTrailerPlate.getText())) {
                Toast.makeText(this, "请至少填写调胎后的车头或挂车牌号", Toast.LENGTH_SHORT).show();
                return false;
            }
        }

        return true;
    }

    private String getTextOrEmpty(TextInputEditText editText) {
        return editText.getText() != null ? editText.getText().toString().trim() : "";
    }

    private String getTextOrEmpty(MaterialAutoCompleteTextView autoCompleteTextView) {
        return autoCompleteTextView.getText() != null ? autoCompleteTextView.getText().toString().trim() : "";
    }

    private void showLoading(boolean show) {
        // 实现加载状态显示
        MaterialButton btnSubmit = findViewById(R.id.btnSubmit);
        btnSubmit.setEnabled(!show);
        btnSubmit.setText(show ? "提交中..." : ("swap".equals(operationType) ? "保存调胎记录" : "确认报废"));
    }

    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }

    // Photo Adapter 内部类
    private class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.PhotoViewHolder> {
        private List<Uri> photos;

        public PhotoAdapter(List<Uri> photos) {
            this.photos = photos;
        }

        @NonNull
        @Override
        public PhotoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_photo, parent, false);
            return new PhotoViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull PhotoViewHolder holder, int position) {
            holder.bind(photos.get(position), position);
        }

        @Override
        public int getItemCount() {
            return photos.size();
        }

        class PhotoViewHolder extends RecyclerView.ViewHolder {
            private ImageView ivPhoto;
            private ImageView ivRemove;

            public PhotoViewHolder(@NonNull View itemView) {
                super(itemView);
                ivPhoto = itemView.findViewById(R.id.ivPhoto);
                ivRemove = itemView.findViewById(R.id.ivRemove);
            }

            public void bind(Uri photoUri, int position) {
                // 加载图片
                Glide.with(itemView.getContext())
                        .load(photoUri)
                        .centerCrop()
                        .into(ivPhoto);

                // 设置删除按钮点击事件
                ivRemove.setOnClickListener(v -> {
                    photos.remove(position);
                    notifyItemRemoved(position);
                    notifyItemRangeChanged(position, photos.size());
                });

                // 点击图片可以查看大图
                ivPhoto.setOnClickListener(v -> showPhotoDetail(photoUri));
            }
        }
    }

    // 显示照片详情的方法
    private void showPhotoDetail(Uri photoUri) {
        // 这里可以实现查看大图的功能
        // 例如：启动一个新的Activity或者显示一个Dialog来展示大图
        Toast.makeText(this, "查看照片", Toast.LENGTH_SHORT).show();
    }

    /**
     * 创建照片部分的MultipartBody.Part列表
     */
    private List<MultipartBody.Part> createPhotoParts() {
        List<MultipartBody.Part> photoParts = new ArrayList<>();

        if (!selectedPhotos.isEmpty()) {
            for (int i = 0; i < selectedPhotos.size(); i++) {
                Uri photoUri = selectedPhotos.get(i);
                try {
                    File photoFile = uriToFile(photoUri, "swap_photo_" + i + ".jpg");
                    if (photoFile != null && photoFile.exists()) {
                        // 获取正确的MIME类型
                        String mimeType = getMimeType(photoUri);
                        MediaType mediaType;

                        if (mimeType != null && !mimeType.isEmpty()) {
                            mediaType = MediaType.parse(mimeType);
                        } else {
                            // 根据文件扩展名推断
                            String ext = getFileExtension(photoFile).toLowerCase();
                            switch (ext) {
                                case ".png":
                                    mediaType = MediaType.parse("image/png");
                                    break;
                                case ".gif":
                                    mediaType = MediaType.parse("image/gif");
                                    break;
                                case ".webp":
                                    mediaType = MediaType.parse("image/webp");
                                    break;
                                default:
                                    mediaType = MediaType.parse("image/jpeg");
                            }
                        }

                        if (mediaType == null) {
                            mediaType = MediaType.parse("image/jpeg");
                        }

                        RequestBody photoRequestBody = RequestBody.create(mediaType, photoFile);
                        MultipartBody.Part photoPart = MultipartBody.Part.createFormData(
                                "swapPhotos",
                                photoFile.getName(),
                                photoRequestBody
                        );
                        photoParts.add(photoPart);
                        Log.d("AddSwapActivity", "成功创建照片Part: " + photoFile.getName() + ", 类型: " + mediaType.toString());
                    }
                } catch (IOException e) {
                    Log.e("AddSwapActivity", "处理照片文件时出错: " + e.getMessage());
                    // 继续处理其他照片，不中断整个流程
                }
            }
        }

        Log.d("AddSwapActivity", "共创建 " + photoParts.size() + " 个照片Part");
        return photoParts;
    }

    // 添加获取MIME类型的方法
    private String getMimeType(Uri uri) {
        ContentResolver contentResolver = this.getContentResolver();
        return contentResolver.getType(uri);
    }

    // 添加获取文件扩展名的方法
    private String getFileExtension(File file) {
        String name = file.getName();
        int lastDot = name.lastIndexOf('.');
        return lastDot != -1 ? name.substring(lastDot) : ".jpg";
    }

    /**
     * 将Uri转换为File
     */
    private File uriToFile(Uri uri, String fileName) throws IOException {
        InputStream inputStream = getContentResolver().openInputStream(uri);
        if (inputStream == null) {
            throw new IOException("无法打开文件流: " + uri);
        }

        File tempDir = new File(getCacheDir(), "temp_swap_photos");
        if (!tempDir.exists()) {
            if (!tempDir.mkdirs()) {
                throw new IOException("无法创建临时目录");
            }
        }

        File tempFile = new File(tempDir, fileName);

        FileOutputStream outputStream = new FileOutputStream(tempFile);
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.close();
        inputStream.close();

        return tempFile;
    }

}

